﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRevitCode.RevitTopologySuite;

namespace YJKRevitCode.SampleAndTest
{
	[Transaction(TransactionMode.Manual)]
	public class CmdRevitDetailCurvePolygonFind : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			return CmdRevitDetailCurvePolygonFind.FindMethod(commandData, true);
		}

		internal static Result FindMethod(ExternalCommandData commandData, bool ifFind)
		{
			UIApplication application = commandData.Application;
			Application application2 = commandData.Application.Application;
			UIDocument activeUIDocument = application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			List<Element> list = activeUIDocument.Selection.PickElementsByRectangle("框选详图线").ToList<Element>();
			List<Curve> list2 = new List<Curve>();
			foreach (Element element in list)
			{
				if (element is DetailCurve)
				{
					list2.Add((element as DetailCurve).GeometryCurve);
				}
			}
			List<RevitPolygonDataBean> collection = null;
			List<RevitPolygonDataBean> collection2 = null;
			RevitPolygonFinder revitPolygonFinder = new RevitPolygonFinder();
			if (revitPolygonFinder.TryGetPolygon(list2, out collection, out collection2, true))
			{
				Transaction transaction = new Transaction(document, "test");
				try
				{
					transaction.Start();
					IEnumerable<ElementId> source = from n in list
					select n.Id;
					document.Delete(source.ToList<ElementId>());
					List<RevitPolygonDataBean> list3 = new List<RevitPolygonDataBean>();
					if (ifFind)
					{
						list3.AddRange(collection);
					}
					else
					{
						list3.AddRange(collection2);
					}
					FilledRegionType useType = CmdRevitFilledRegionTopology.FindFilledRegionType(document);
					CmdRevitFilledRegionTopology.CreatFilledRegion(document, list3, useType);
					transaction.Commit();
				}
				catch (Exception)
				{
					transaction.RollBack();
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
